package com.kuangstudy.controller.shopcart;

import com.kuangstudy.entity.ShopCart;
import com.kuangstudy.service.creatorid.IdCreatorService;
import com.kuangstudy.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author 飞哥
 * @Title: 学相伴出品
 * @Description: 我们有一个学习网站：https://www.kuangstudy.com
 * @date 2021/5/21 17:24
 */
@Controller
public class CookieShopCartController {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private HttpServletResponse response;
    @Autowired
    private IdCreatorService idCreatorService;

    // 1: 生成全局唯一的id，并写入到cookie中
    public String getCookieCartId() {
        // 1: 获取请求的cookie,查看是否已经创建过cookie了
        // 2：如果创建cookie，直接方法
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("kssshopchartid")) {
                    return cookie.getValue();
                }
            }
        }
        // 3：如果没有创建，就在缓存中创建一个
        Long incrmentid = idCreatorService.incrmentid("id:creator:shopcart");
        // 4：并且同时在cookie中创建一个购物车的id
        Cookie cookie = new Cookie("kssshopchartid", String.valueOf(incrmentid));
        response.addCookie(cookie);
        // 5: 返回创建好的购物车id
        return incrmentid + "";
    }


    // 1: 添加商品到购物车中
    @ResponseBody
    @PostMapping("/hash/cookie/shopcart/add")
    public R addCookieShopCart(ShopCart shopCart) {
        // 1: 获取cookie存储购物车的key
        String cartid = getCookieCartId();
        String key = "shopcart:cookie:" + getCookieCartId();
        // 2：判断key是否已经存在redis中
        Boolean hasKey = this.redisTemplate.opsForHash().getOperations().hasKey(key);
        // 3: 如果hasKey存在说明该商品已经在购物车中
        if (hasKey) {
            // 4：如果存在，就直接覆盖最新的数据进去
            this.redisTemplate.opsForHash().put(key, shopCart.getProductid().toString(), R.beanToMap(shopCart));
        } else {
            // 5：如果不存在，就直接覆盖最新的数据进去&设置过期时间30天
            this.redisTemplate.opsForHash().put(key, shopCart.getProductid().toString(), R.beanToMap(shopCart));
            this.redisTemplate.expire(key, 30, TimeUnit.DAYS);
        }
        return R.ok();
    }

    // 2: 修改购物车的数量
    @ResponseBody
    @PostMapping("/hash/cookie/shopcart/update")
    public R updateCookiesShopcartnum(ShopCart shopCart) {
        // 1: 存储购物车的缓存key
        String key = "shopcart:cookie:" + getCookieCartId();
        // 2：修改购物车的数量
        this.redisTemplate.opsForHash().put(key, shopCart.getProductid().toString(), R.beanToMap(shopCart));
        return R.ok();
    }


    // 3： 删除购物车的某个商品
    @ResponseBody
    @PostMapping("/hash/cookie/shopcart/del")
    public R delCookieshopcart(Long productid) {
        // 1: 存储购物车的缓存key
        String key = "shopcart:cookie:" + getCookieCartId();
        // 2：修改购物车的数量
        this.redisTemplate.opsForHash().delete(key, productid.toString());
        return R.ok();
    }


    // 4: 查询购物车中所有的数据信息
    @ResponseBody
    @GetMapping("/hash/cookie/shopcart/selectall")
    public R selectCookieshopcart() {
        // 1: 存储购物车的缓存key
        String key = "shopcart:cookie:" + getCookieCartId();
        // 2：从redis中获取购物车中的数量
        Long size = this.redisTemplate.opsForHash().size(key);
        // 3：从redis中获取购物车中所有的商品
        Map<String, Map<String, Object>> entries = this.redisTemplate.opsForHash().entries(key);
        // 4: 创建容器集合，获取产品放入到集合中
        List<Map<String, Object>> resultList = new ArrayList<>();
        // 5: 计算总金额
        double totalmoney = 0d;
        for (Map.Entry<String, Map<String, Object>> entry : entries.entrySet()) {
            resultList.add(entry.getValue());
            totalmoney += Integer.parseInt(String.valueOf(entry.getValue().get("productnum"))) *
                    Double.parseDouble(String.valueOf(entry.getValue().get("productprice")));
        }
        return R.ok().data("total", size)
                .data("totalmoney", totalmoney)
                .data("datas", resultList);
    }


    // 4: 合并购物车
    @ResponseBody
    @GetMapping("/hash/cookie/shopcart/merge")
    public R MergetCookieshopcart(Long userid) {

        // 1：提出未登录的cookie购物车中的数据信息
        String cookiekey = "shopcart:cookie:" + getCookieCartId();
        Map<String, Map<String, Object>> cookieMap = this.redisTemplate.opsForHash().entries(cookiekey);

        // 2：提出登录的购物车的数据信息
        String loginkey = "shopcart:user:" + userid;
        //3：调用putall方法进行合并
        this.redisTemplate.opsForHash().putAll(loginkey, cookieMap);
        // 4: 删除redis中cookie缓存的数据
        this.redisTemplate.delete(cookiekey);
        // 5: 删除浏览器cookie
        Cookie cookie = new Cookie("kssshopchartid", null);
        cookie.setMaxAge(0);
        response.addCookie(cookie);

        return R.ok().data("cookie", "is clear");
    }


}
